// pages/login/login.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sessionKey: '',
    openid: '',
    phone: "",
    redirect: ''
  },
  cancel: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  getPhoneNumber(e) {
    var that = this
    console.log(e)
    if (e.detail.iv && e.detail.encryptedData)
      wx.request({
        url: 'https://hpy.izhixiu.cn/api/front/appletPay/appletPay',
        method: 'POST',
        data: {
          type: 'getPhone',
          session_key: this.data.sessionKey,
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData
        },
        success: function (res) {
          let _phone = JSON.parse(res.data.data[0]).phoneNumber
          that.setData({
            phone: _phone
          })

          wx.navigateTo({
            url: '/pages/login_auth/login_auth?phone=' + that.data.phone + '&openid=' + that.data.openid + (that.data.redirect ? ('&redirect=' + that.data.redirect) : ''),
          })
        },
        fail: function(err) {
          console.log(err)
        }
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if(options.redirect) {
      this.setData({
        redirect:options.redirect
      })
    }
    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: 'https://hpy.izhixiu.cn/api/front/appletPay/appletPay',
            method: 'POST',
            data: {
              type: 'getSessionKey',
              code: res.code
            },
            success: function (ress) {
              that.setData({
                sessionKey: ress.data.data.session_key,
                openid: ress.data.data.openid
              })
            }
          })

        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})